
import java.util.ArrayList;

import javax.swing.JPanel;

import fr.uhp.nobrain.games.GameState;
import fr.uhp.nobrain.highscore.Score;
import fr.uhp.nobrain.tools.Observateur;
import fr.uhp.nobrain.tools.TimerControl;


public class GameStateMock extends Thread  implements GameState {

	private static final int REFRESH_DELAY = 5000;
	private String problem;
	private int num = 0;
	private ArrayList<Observateur> listObservateur = new ArrayList<Observateur>();
	private Thread t;
	private GameViewMock view;
	private boolean run = true;
	private TimerControl timer;
	private int timeRemaining = 1;
	private Score currentScore;
	
	public GameStateMock() {
		this.t = new Thread(this);
		this.view = new GameViewMock(this);
		this.timer = new TimerControl();
		this.currentScore = new Score();
	}
	
	public void run() {
		while(run) {
			this.problem = "1 + " + (++num) + " = ?";
			this.currentScore.setScore(currentScore.getScore() + 5);
			
			this.updateObservateur();
			
			try {
				Thread.sleep(REFRESH_DELAY);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public int exit() {
		this.run = false;
		return currentScore.getScore();
	}

	@Override
	public JPanel getPanel() {
		return view.getPanel();
	}

	@Override
	public void start(int arg0) {
		t.start();
		timer.addObservateur(new Observateur(){
			@Override
			public void update(String o) {
				timeRemaining = Integer.valueOf(o);
				if (timeRemaining == 0)
					exit();
			}
		});
		timer.start(arg0);
		
		currentScore.addObservateur(new Observateur(){
			@Override
			public void update(String o) {
				currentScore.setScore(Integer.valueOf(o));
			}
		});
		currentScore.start();
	}
	
	public void addObservateur(Observateur obs) {
		this.listObservateur.add(obs);
	}

	public void delObservateur() {
		this.listObservateur = new ArrayList<Observateur>();
	}

	public void updateObservateur() {
		String s = this.toString();
		for(Observateur obs : this.listObservateur )
			obs.update(s);
	}
	
	@Override
	public String getGameName() {
		return "GameStateMock";
	}

	@Override
	public String toString() {
		return problem;
	}

	@Override
	public TimerControl getTimer() {
		return timer;
	}
	
	@Override
	public int getScore() {
		return currentScore.getScore();
	}
}
